<template>
  <el-dropdown
    class="ui-dropdown"
    @command="handleCommandChange"
    @visible-change="handleVisibleChange"
  >
    <div ref="handle" class="ui-dropdown__handle" @mouseenter="handleHandleMouseenter">
      <slot name="reference" :visible="visible">
        <ui-button :icon="icon" :type="type" :size="size">{{ label }}<i class="el-icon-arrow-down el-icon--right"></i></ui-button>
      </slot>
    </div>
    <el-dropdown-menu slot="dropdown" :style="{'min-width': menuMinWidth}">
      <slot />
    </el-dropdown-menu>
  </el-dropdown>
</template>
<script>
import UiButton from '../button'
import ElDropdown from 'element-ui/lib/dropdown'
import ElDropdownMenu from 'element-ui/lib/dropdown-menu'

import 'element-ui/lib/theme-chalk/dropdown.css'
import 'element-ui/lib/theme-chalk/dropdown-menu.css'
import 'element-ui/lib/theme-chalk/dropdown-item.css'

export default {
  name: 'UiDropdown',
  components: {
    UiButton,
    ElDropdown,
    ElDropdownMenu
  },
  props: {
    label: {
      type: String
    },
    icon: {
      type: String
    },
    type: {
      type: String,
      default: 'primary'
    },
    size: {
      type: String,
      default: 'small'
    }
  },
  data() {
    return {
      visible: false,
      menuMinWidth: null
    }
  },
  methods: {
    handleVisibleChange(visible) {
      this.visible = visible
    },
    handleHandleMouseenter() {
      this.menuMinWidth = this.$refs.handle.clientWidth + 'px'
    },
    handleCommandChange(evt) {
      this.$emit('command', evt)
    }
  }
}
</script>
<style lang="less">
.ui-dropdown{
  vertical-align: top;
}
</style>
